package tests

import (
	"testing"

	"golang.org/x/exp/maps"
	"notabug.org/Umnik/GoAndroidSDK/v2/components/sdk/buildTools/apksigner"
)

func newSignRead(t *testing.T, funcName string) *apksigner.Apksigner {
	t.Helper()
	a, err := apksigner.NewApkSignerLastVersion(*newSdk(t, t.Name()))
	if !testErr(t, funcName, err) {
		return nil
	}
	return a
}

func dumpSign(file string, funcName string, signer *apksigner.Apksigner, t *testing.T) []byte {
	t.Helper()
	b, err := signer.DumpSignatureInfo(file, false)
	if !testErr(t, funcName, err) {
		t.Errorf("data: %s\nerr: %s", string(b), err)
		return nil
	}
	return b
}

func verifyInfo(t *testing.T, file string, funcName string) *apksigner.VerifyInfo {
	t.Helper()
	sr := newSignRead(t, funcName)
	b := dumpSign(file, funcName, sr, t)
	res := apksigner.ParseDumpSignatureInfoFromBytes(b)
	return &res
}

func TestSignV31(t *testing.T) {
	t.Parallel()
	info := verifyInfo(t, sign31File, t.Name())
	t.Log(info)
}

func TestVirifyInfo1(t *testing.T) {
	t.Parallel()
	vi := verifyInfo(t, emptyValFile, t.Name())
	if !maps.Equal(vi.SignInfo[0].CertDN, map[string]string{"O": "Ledger SAS", "C": "FR", "L": "Paris"}) {
		t.Errorf("Bad signature: %s", vi.SignInfo[0].CertDN)
	}

}

func TestVirifyInfo2(t *testing.T) {
	t.Parallel()
	vi := verifyInfo(t, goodApkFile, t.Name())
	if !maps.Equal(vi.SignInfo[0].CertDN, map[string]string{"C": "UK", "CN": "FDroid", "L": "ORG", "O": "fdroid.org", "OU": "FDroid", "ST": "ORG"}) {
		t.Errorf("Bad signature: %s", vi.SignInfo[0].CertDN)
	}

}

func TestVerifyInfo3(t *testing.T) {
	t.Parallel()
	vi := verifyInfo(t, splitBaseFile, t.Name())
	if !maps.Equal(vi.SignInfo[0].CertDN, map[string]string{"CN": "Empatika LLC", "O": "Empatika LLC"}) {
		t.Errorf("Bad signature: %s", vi.SignInfo[0].CertDN)
	}

}
